package thread;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/***
 * 线程池异常处理方式
 * 1.Runnable 里自己try-catch
 * 2、future get 自己处理
 * 3.java.util.concurrent.ThreadPoolExecutor#afterExecute(java.lang.Runnable, java.lang.Throwable) 可以访问异常 但不能截获
 * 4.ThreadFactory 自定义，对每个Thread 赋值setUncaughtExceptionHandler
 */
public class ThreadPoolException {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(new Thread1());

        Future<?> future = executorService.submit(() -> {
            int i = 0;
            i = 1 / i;
        });
        System.out.println(future.isCancelled());
        System.out.println(future.isDone());
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(future.isCancelled());
        System.out.println(future.isDone());


        ExecutorService executorService1 = new ThreadPoolExecutor(2, 2, 60
                , TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new MyFactory());
        executorService1.execute(new Thread1());
        executorService1.execute(new Thread1());
        executorService1.execute(new Thread1());
        System.in.read();
    }
}
class Thread1 implements Runnable{
    @Override
    public void run() {
        try {

            System.out.println("in0");
            throw new RuntimeException("lll");
        }catch (Exception e){
            System.out.println(e);
            throw new RuntimeException("mmm");
        }
    }
}

class MyFactory implements ThreadFactory{
    AtomicInteger integer =new AtomicInteger(1);

    @Override
    public Thread newThread(Runnable r) {
        SecurityManager s = System.getSecurityManager();
        ThreadGroup group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        System.out.println("jjk");
        Thread my = new Thread(group,r,"my"+integer.getAndIncrement());
        if (my.isDaemon())
            my.setDaemon(false);
        if (my.getPriority() != Thread.NORM_PRIORITY)
            my.setPriority(Thread.NORM_PRIORITY);
        my.setUncaughtExceptionHandler((t, e) -> {
            System.out.println("=="+"异常吃掉了");

        });

        return my;
    }
}
